package com.trdcore.zyzkt.service.impl;

import com.alibaba.fastjson2.JSON;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.trdcore.zyzkt.service.FileService;
import com.trdcore.zyzkt.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;


@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {

        String endpoint= ConstantPropertiesUtil.END_POINT;
        String bucketName =ConstantPropertiesUtil.BUCKET_NAME;
        String secretId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String secretKey=ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        COSCredentials cred=new BasicCOSCredentials(secretId,secretKey);
        Region region= new Region(ConstantPropertiesUtil.END_POINT);
        ClientConfig clientConfig=new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
        COSClient cosClient=new COSClient(cred,clientConfig);
        String key= UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();
        String dateUrl=new DateTime().toString("yyyy/MM/dd");
        key=dateUrl+"/"+key;
        try {
            InputStream inputStream=file.getInputStream();

            ObjectMetadata objectMetadata=new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            PutObjectRequest putObjectRequest=new PutObjectRequest(bucketName,key,inputStream,objectMetadata);
            PutObjectResult putObjectResult=cosClient.putObject(putObjectRequest);
            System.out.println(JSON.toJSONString(putObjectResult));
            String url="https://"+bucketName+"."+"cos"+"."+endpoint+".myqcloud.com"+"/"+key;
            return url;
        }
        catch (Exception clientException){
            clientException.printStackTrace();
            return null;
        }
    }
}
